package com.mingxingyi.applet.interceptor;


import com.mingxingyi.applet.constant.UserLoginConstant;
import com.mingxingyi.base.context.AppletContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(UserLoginConstant.TOKEN_NAME);
        String userId;
        log.info("token效验:{}", token);
        if (StringUtils.isNotBlank(token)) {
            String[] split = token.split(UserLoginConstant.STRIKE);
            if (split.length != 2) {
                response.setStatus(401);
                return false;
            }
            token = split[0];
            userId = split[1];
        } else {
            response.setStatus(401);
            return false;
        }
        //2、校验令牌
        try {

            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            String storeToken = stringStringValueOperations.get(UserLoginConstant.WX_ACCESS_TOKEN_REDIS_KEY + UserLoginConstant.STRIKE + userId);
            if(StringUtils.isNotBlank(token)) {
                // 有token则放行
                if (StringUtils.isNotBlank(storeToken)
                        && storeToken.equals(token)) {
                    log.info("token效验放行");
                    AppletContext.setCurrentUserId(Integer.parseInt(userId));
                    return true;
                }else {
                   String temporaryStoreToken = stringStringValueOperations.get(UserLoginConstant.WX_ACCESS_TOKEN_TEMPORARY_REDIS_KEY + UserLoginConstant.STRIKE + userId);
                    if (StringUtils.isNotBlank(temporaryStoreToken)
                            && temporaryStoreToken.equals(token)) {
                        log.info("token效验放行");
                        AppletContext.setCurrentUserId(Integer.parseInt(userId));
                        return true;
                    }
                }
            }

        } catch (Exception ex) {
            response.setStatus(401);
            return false;
        }
        response.setStatus(401);
        return false;
    }
}
